package cn.huaqingcheng.tianshu.core.start.service;

import cn.huaqingcheng.tianshu.core.start.model.Site;
import cn.huaqingcheng.tianshu.core.start.param.SiteParam;
import cn.huaqingcheng.tianshu.core.start.param.SortParam;
import cn.huaqingcheng.tianshu.core.start.repository.SiteRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * SiteServiceImpl
 */
@Service
@RequiredArgsConstructor
public class SiteServiceImpl implements SiteService {

    private final SiteRepository siteRepository;


    @Override
    @Transactional(readOnly = true)
    public List<Site> getList(Long accountId, Long groupId) {
        return siteRepository.getList(accountId, groupId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Site create(SiteParam site, Long accountId) {
        site.setAccountId(accountId);
        return siteRepository.save(site);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Site update(SiteParam site, Long accountId) {
        siteRepository.selectById(Objects.requireNonNull(site.getId()))
                .filter(i -> i.getAccountId().equals(accountId))
                .orElseThrow();
        return siteRepository.update(site);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSort(List<SortParam> params, Long accountId) {
        List<Long> ids = params.stream()
                .map(SortParam::id)
                .toList();
        Map<Long, Site> mapping = siteRepository.selectMapByIds(ids);

        List<Site> list = params.stream()
                .map(param -> {
                    Site site = mapping.get(param.id());
                    if (site == null || !Objects.equals(site.getAccountId(), accountId)) {
                        return null;
                    }
                    return site.setSort(param.sort());
                })
                .filter(Objects::nonNull)
                .toList();
        siteRepository.update(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(List<Long> ids, Long accountId) {
        if (ids.isEmpty()) {
            return;
        }
        siteRepository.remove(ids, accountId);
    }

}
